package com.cmwa.solution.sys.attach.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cmwa.ec.base.util.SpringUtil;
import com.cmwa.solution.base.controller.BaseController;
import com.cmwa.solution.base.entity.Employee;
import com.cmwa.solution.base.entity.Result;
import com.cmwa.solution.exception.FileUploadException;
import com.cmwa.solution.exception.ValidateFailedException;
import com.cmwa.solution.sys.attach.entity.AttachVo;
import com.cmwa.solution.sys.attach.service.AttachService;
import com.cmwa.solution.sys.dictionary.entity.DictionaryVo;
import com.cmwa.solution.utils.DateUtils;
import com.cmwa.solution.utils.FileUtil;
import com.cmwa.solution.utils.SessionUtils;
import com.cmwa.solution.utils.cached.DictionaryCached;

import net.sf.json.JSONObject;

/**
 * @author zhengqq
 * @date 2018年9月3日
 */
@Controller
@RequestMapping(value = "/sys/attach")
public class AttachController extends BaseController{

	@Resource
	private AttachService attachService;

	private static Logger logger = LogManager.getLogger(AttachController.class);

	/*
	 * /** 保存单个文件到服务器
	 * 
	 * @param request
	 * 
	 * @param response
	 * 
	 * @throws FileUploadException
	 */
	@RequestMapping("uploadFile4Create")
	public void uploadFile4Create(HttpServletRequest request,HttpServletResponse response, 
		@RequestParam(value="resourceSign", required=false, defaultValue="")String resourceSign) throws FileUploadException {
		AttachVo attachVo = FileUtil.saveSingleFileToServer(request, "file");
		if(StringUtils.isNotBlank(resourceSign)){
			attachVo.setResourceSign(resourceSign);
		}
		attachService.saveValidAttach(attachVo);
		try {
			PrintWriter out = response.getWriter();
			response.setContentType("application/json;charset=UTF-8");
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("isOK", attachVo.getIsOK());
			jsonObj.put("errorMessage", attachVo.getErrorMessage());
			jsonObj.put("id", attachVo.getAttId());
			jsonObj.put("name", attachVo.getAttName());
			jsonObj.put("resourceSignName", attachVo.getResourceSignName());
			out.write(jsonObj.toString());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("上传文件出错：", e);
		}
	}

	@RequestMapping("uploadFile4Update")
	public void uploadFile4Update(HttpServletRequest request, HttpServletResponse response, String type, String objId) throws FileUploadException {
		AttachVo attachVo = FileUtil.saveSingleFileToServer(request, "file");
		attachService.saveValidAttach(attachVo);
		try {
			PrintWriter out = response.getWriter();
			response.setContentType("application/json;charset=UTF-8");
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("id", attachVo.getAttId());
			jsonObj.put("name", attachVo.getAttName());
			out.write(jsonObj.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 向T_ATTACH_INFO插入数据
	 * @author ex-hejm
	 * @date 2018年10月29日 下午3:13:45
	 * @param attpar
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("addAttachInfo")
	public void addAttachInfo(@RequestParam("attpar") String attpar, HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获取当前用户
		Employee employee = SessionUtils.getEmployee();
		String empId = employee.getID();

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {
			// 常规变量控制
			long MAX_FILE_SIZE = 10 * 1024 * 1024 * 3;// 30M
//			String attPar = request.getParameter("attpar"); // 附件参数
			String isOK = "0";
			String errorMessage = "附件上传失败！";
			String fileId = null;
			String fileName = "";
			String filePath = null;
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

			// 检查文件大小，以减轻对服务器内存的压力
			int contextLength = request.getContentLength();
			if (contextLength > (MAX_FILE_SIZE + 460)) {
				isOK = "1";
				errorMessage = "错误：上传的文件超出大小限制！请上传附件大小为30M以下的文件";
			} else {
				List<MultipartFile> fileList = multipartRequest.getFiles("uploadFile_" + attpar);

				String dateTimeStr = DateUtils.getNowStr(DateUtils.DATE_FORMAT_yMdHms_EN1);
				// 获取附件的默认文件夹路径,不存在就创建文件夹
				String headPath = SpringUtil.getProperty("sys.tmpFileBasePath") + File.separator + dateTimeStr.substring(0, 4) + File.separator + dateTimeStr.substring(0, 8);
				File tempDir = new File(headPath);
				if (!tempDir.exists()) {// 创建目录
					tempDir.mkdirs();
				}
				headPath = headPath + File.separator + dateTimeStr;

				if (fileList.size() > 0) {
					MultipartFile mf = fileList.get(0);
					fileName = mf.getOriginalFilename();
					if (fileName == null) {
						fileName = "";
					}
					String extend = "";
					if (fileName.lastIndexOf(".") != -1) {
						extend = fileName.substring(fileName.lastIndexOf("."));
					}
					filePath = headPath + getUUID() + extend;
					mf.getInputStream();
					byte[] bytes = mf.getBytes();
					File f = new File(filePath);
					OutputStream stream = new FileOutputStream(f);
					stream.write(bytes);
					if (stream != null) {
						stream.close();
					}

					AttachVo attachVo = new AttachVo();
					attachVo.setAttName(fileName); // 附件名称
					attachVo.setAttPath(filePath);// 存放路径
					attachVo.setCreateId(empId); // 创建人
					attachService.addAttach(attachVo);
					String attId = attachVo.getAttId();
					if (attId == null) {
						fileId = "";
					} else {
						fileId = attId.toString();
					}

				} else {
					isOK = "1";
					errorMessage = "错误：上传的文件不存在！";
				}

			}

			if (isOK.equals("1")) {
				out.println("{msg:\"" + errorMessage + "\",isOK:" + isOK + "}");
			} else {
				if (fileId == "") {
					out.println("{msg:\"错误：返回ATTID为空\",isOK: 1 }");
				} else {
					out.print("{\"attId\":" + fileId + ",\"isOK\":\"" + 0 + "\",\"attName\":\"" + fileName + "\"}");
				}
			}
		} catch (IOException e) {
			out.println("{msg:\"附件上传失败！\",isOK:1}");
		}

	}

	/**
	 * 向T_ATTACH_INFO表删除数据
	 * @author ex-hejm
	 * @date 2018年10月29日 下午3:13:54
	 * @param attId
	 * @return
	 */
	@RequestMapping("delAttachInfo")
	@ResponseBody
	public Object delAttachInfo(@RequestParam("attId") String attId){
		AttachVo attachVo = new AttachVo();
		attachVo.setAttId(attId);
		String isOK = "0";
		String msg = "";
		Map<String, String> signState = new HashMap<String, String>();
		if (attId != null && !"".equals(attId)) {
			try {
				attachVo = attachService.findById(attId);
				attachService.deleteAttach(attachVo);//删除附件
				attachService.deleteAttachRel(attachVo);//删除附件关联关系
				if (attachVo != null && attachVo.getAttPath() != "") {
					File f = new File(attachVo.getAttPath());
					f.delete();
				}
				isOK = "1";
			} catch (Exception e) {
				msg = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
				if (StringUtils.contains(msg, "FK_T_ATT_ARRANGEMENT_ATTCH")) {
					msg = "附件删除异常";
				}
			}
		} else {
			msg = "ATTID不能为空";
		}
		signState.put("isOK", isOK);
		signState.put("msg", msg);
		return signState;
	}

	/**
	 * 下载
	 * @author ex-hejm
	 * @date 2018年10月29日 下午3:14:02
	 * @param attId
	 * @param request
	 * @param response
	 * @param isUpload
	 * @throws IOException
	 * @throws ValidateFailedException
	 */
	@RequestMapping("downloadAttach")
	public void downloadAttach(@RequestParam("attId") String attId, HttpServletRequest request, HttpServletResponse response, @RequestParam(value="isUpload", required=false) String isUpload) throws IOException,ValidateFailedException {
		attachService.downloadAttach(attId, request, response, isUpload);
	}

	/**
	 * 压缩下载
	 * @param attIds
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("downloadAttachZip")
	public void downloadAttachZip(@RequestParam("attIds") String attIds, @RequestParam("names") String names, HttpServletRequest request, HttpServletResponse response) throws IOException {
		attachService.downloadAttachZip(attIds, names, request, response);
	}
	
	private String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	/**
	 * 加载附件特殊字符
	 * @return
	 */
	@RequestMapping("/querySpecialCharacter")
	@ResponseBody
	public Map<String, String> querySpecialCharacter(){
		Map<String, String> map = new HashMap<String, String>();
		StringBuffer specialName = new StringBuffer();
		StringBuffer specialValue = new StringBuffer();
		String status = "";
		List<DictionaryVo> type = DictionaryCached.getDictionaryByType("SPECIAL_CHARACTER");
		if(CollectionUtils.isNotEmpty(type)){
			for (DictionaryVo dictionaryVo : type) {
				specialName.append(dictionaryVo.getDctName()).append(",");
				specialValue.append(dictionaryVo.getDctValue()).append(",");
			}
			status = "true";
		}
		//加载文档类型
//		String menu = documentService.printDocumentTree();
//		map.put("documentTypeList",menu);
		map.put("specialName", specialName.substring(0, specialName.length()-1).toString());
		map.put("specialValue", specialValue.substring(0, specialValue.length()-1).toString());
		map.put("status", status);
		return map;
	}
	
	/**
	 * 根据附件ID查找所有附件
	 */
	@RequestMapping("/queryAttachByIds")
	@ResponseBody
	public Object queryAttachByIds(@RequestParam(value="attachIds", required=false, defaultValue="") String attachIds){
		String[] attIds = null;
		List<AttachVo> attachLst = null;
		Result<Object> result = new Result<Object>();
		result.setMessage("成功");
		result.setSuccess(true);
		try {
			if(StringUtils.isNotEmpty(attachIds)){
				attIds = attachIds.split(",");
				attachLst = attachService.findByIds(attIds);
				result.setObject(attachLst);
			 }
		} catch (Exception e) {
			 result.setSuccess(false);
			 result.setMessage("失败：" + e.getMessage());
		}
		return result;
	}
	
}
